#!/bin/sh

path=$(uci get -q youku.@path[0].path)
if [ "$(uci get -q youku.youku.enable)" = "0" ]
then
	[ "$(cat /etc/rc.local|grep /etc/oldg)" ] && sed -i 's/echo \"0\">\/etc\/oldg//g' /etc/rc.local
	[ "$(cat /etc/crontabs/root|grep /lib/today)" ] && sed -i 's/20 \*\/1 \* \* \* sh \/lib\/today > \/dev\/null  2>&1//g' /etc/crontabs/root
	killall -9 ikuacc
	exit 0
else
	[ "$(cat /etc/rc.local|grep /etc/oldg)" ] || sed -i "/exit 0/iecho \"0\">\/etc\/oldg" /etc/rc.local
	[ "$(cat /etc/crontabs/root|grep /lib/today)" ] || echo "20 */1 * * * sh /lib/today > /dev/null  2>&1">>/etc/crontabs/root
fi

if [ "$path" = "" ]
then
	killall -9 ikuacc
	exit 0
fi 
sleep 2
wksn="$(uci get -q youku.youku.opsn)"
str="--device-serial-number="0000$wksn" --mobile-meta-path="$path/youku/meta" --mobile-data-path="
i=0
while [ "$(uci get -q youku.@path[$i].path)" != "" ]
do
partsize=`df -m | grep $(uci get -q youku.@path[$i].path) | awk '{print $2 }'`
[ ${partsize} -gt 500 ] && {
	if [ $(uci get -q youku.@path[$i].pathhc) != "" ]
	then
		hc=":$(uci get -q youku.@path[$i].pathhc)"
	else
		hc=""
	fi
	str="$str$(uci get -q youku.@path[$i].path)/youku/data$hc;"
	i=$(($i+1))
	}
done

while true
do
	sleep 20
	if [ "$(uci get -q youku.youku.cqboot)" = "$(date +%H%M)" ]
	then
		sleep 30
		if [ "$(uci get -q youku.youku.ikrebot)" = "1" ]
		then
			killall ikuacc
			sleep 3
		else
			reboot
		fi
	fi
	sleep 5

	if [ "$(uci get -q youku.youku.enable)" = "1" ]
	then
		if [ "$(pidof ikuacc)" = "" ]
		then
			sleep 5
			ikuacc  ${str%?}  &
			sleep 5
			sdt="1"
		fi
	fi
	if [ "$sdt" = "1" ]
	then
		wget -O - 'http://127.0.0.1:8908/peer/limit/network/set?upload_model='"$(uci get -q youku.youku.wkmod)" > /dev/null 2>&1
		sleep 2
		sdt="0"
	fi
	if [ "$(uci get -q youku.youku.enable)" = "0" ]
	then
		killall -9 ikuacc
		exit 0
	fi
done

